package com.yhx.controller;

import com.yhx.iservice.IOrderSettingService;
import com.yhx.pojo.Ordersetting;
import com.yhx.utils.ExcelUtils;
import com.yhx.utils.MessageConstant;
import com.yhx.utils.MyFileUtils;
import com.yhx.utils.Result;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/ordersetting")
public class OrderSettingController {
    @Reference
    private IOrderSettingService iOrderSettingService;
    @Value("${download.path}")
    private String path;
    @RequestMapping("upload")
    public Result save(@RequestParam("excelFile") MultipartFile multipartFile){
        try {
            //文件上传
            File file =MyFileUtils.upload(multipartFile, path);
            //上传文件失败
            if (file == null) {
                return new Result(false, MessageConstant.UPLOAD_FAIL);
            }
            //将文件读取出来
            List<Ordersetting> list = ExcelUtils.ExcelgetList(file);
            //调用serviceimpl
            Result save = iOrderSettingService.save(list);
            return save;
        } catch (IOException | InvalidFormatException e) {
            e.printStackTrace();
            return new Result(false, "表格中的数据存在异常");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.ORDERSETTING_FAIL);
        }
    }

    @GetMapping("/{time}")
    public Result list(@PathVariable String time){
        try {
            Result list = iOrderSettingService.list(time);
            return list;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.ORDERSETTING_FAIL);
        }
    }
    @GetMapping("/{time}/{number}")
    public Result update(@PathVariable Date time, @PathVariable Integer number){
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            String format1 = format.format(time);
            Date parse = format.parse(format1);
            Ordersetting ordersetting = new Ordersetting(0, parse, number, 0);
            return iOrderSettingService.update(ordersetting);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.ORDERSETTING_FAIL);
        }
    }


}
